package com.shushan.mixedexam;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.AnimationDrawable;
import android.media.SoundPool;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.shushan.mixedexam.sync.ExamFragment;

import com.android.net.bean.NetRetBean;
import com.android.net.core.common.RequestType;
import com.android.net.helper.NetHelper;
import com.android.net.listener.common.CallbackCode;
import com.android.net.url.UrlParse;
import com.shushan.base.BaseActivity;
import com.shushan.base.Constants;
import com.shushan.base.ScreenManager;
import com.shushan.mixedexam.adapter.ExamFragmentAdapter;
import com.shushan.mixedexam.bean.ExerciseResultBean;
import com.shushan.mixedexam.bean.MutiExerciseBean;
import com.shushan.mixedexam.bean.MutiExerciseOptionBean;
import com.shushan.mixedexam.bean.MutiExercisePaperBean;
import com.shushan.mixedexam.englishwords.EnglishWordsExam3Fragment;
import com.shushan.mixedexam.englishwords.EnglishWordsExamFragment;
import com.shushan.mixedexam.hearing.HearingExamFragment;
import com.shushan.mixedexam.readrecite.ReadReciteExamFragment;
import com.shushan.mixedexam.readrecite.bean.ReadReciteDataBean;
import com.shushan.mixedexam.speaking.SpeakingExamFragment;
import com.shushan.mixedexam.strangewords.StrangeWordsExam2Fragment;
import com.shushan.mixedexam.strangewords.StrangeWordsExamFragment;
import com.shushan.mixedexam.sync.FillBlankExamFragment;
import com.shushan.network.UrlCommParse;
import com.shushan.network.UrlConst;
import com.shushan.network.listener.NetSingleCommListener;
import com.shushan.network.listener.NetStrCommListener;
import com.shushan.service.PostExerciseServer;
import com.shushan.service.PostGameTimeServer;
import com.shushan.shushanbao.BabyApplication;
import com.shushan.shushanbao.BuildConfig;
import com.shushan.shushanbao.R;
import com.shushan.ui.AnimationsContainer;
import com.shushan.ui.CustomDialog;
import com.shushan.ui.NoScrollViewPager;
import com.shushan.util.DownloadUtil;
import com.shushan.util.ExamAudioPlayUtil;
import com.shushan.util.Session;
import com.shushan.util.ToolUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @ClassName: MixedExamActivity
 * @Desciption: //混合题型考试界面
 * @author: zhangshihao
 * @date: 2018-06-19
 */
public class MixedExamActivity extends BaseActivity implements View.OnClickListener, OnAnswerSelectListener, ViewPager.OnPageChangeListener,
        DownloadUtil.OnDownloadFinishedListener,DownloadUtil.OnSourceExistListener{

    private static final String TAG = "MixedExamActivity";

    private NoScrollViewPager viewPager;
    private ExamFragmentAdapter examFragmentAdapter;
    private ImageView ivRight, ivWrong;
    private TextView examTimeTextView;
    private TextView tvTopicTotalNum, tvCurrentNum;
    private ImageView examButton;
    private Button btnNextTopic;
    private RelativeLayout rlVpContainer;
    private int vpWidth, vpHeight;
    private int examTime = 0;
    private boolean doneFinish = false;
    private int pageIndex = 0;
    private BabyApplication shuShanApplication = BabyApplication.getInstance();
    private int examType;//1、同步练习 2、智能练习 3、边学边练 4、重点练习 5、难点练习 6、易错练习 7、专项练习
    private int jumpType;
    private int subjectId;//边学边练科目id
    private int videoId;//边学边练视频id
    private MutiExercisePaperBean exercisePaperBean;
    private List<MutiExerciseBean> chineseExerciseBeans;
    private List<MutiExerciseBean> mathExerciseBeans;
    private List<MutiExerciseBean> englishExerciseBeans;
    private List<MutiExerciseBean> paperExerciseBeans;
    private int rightNum = 0;
    private int wrongNum = 0;
    private int noRecordIndex = 0;
    //试题上报参数：{
    private int rightOptionId = 0;
    private int option_result = 0;
    private int my_option = 0;
    //@}

    private SoundPool soundPool;//播放短小音频
    private int[] soundResIds = {R.raw.right_audio, R.raw.wrong_audio};
    private HashMap<Integer, Integer> soundIdMap = new HashMap<>();
    private AnimationsContainer.FramesSequenceAnimation rightAnimation;
    private AnimationsContainer.FramesSequenceAnimation wrongAnimation;
    private AlreadyScoreReceiver alreadyScoreReceiver;

    private PowerManager.WakeLock wakeLock;
    Handler scrollHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {
                case 0:
                    viewPager.setCurrentItem(msg.arg1, true);
                    break;
                default:
                    break;
            }
        }
    };

    private String[] jsonArr = {"{\"group\":0,\"left\":88,\"top\":57.60000000000002,\"width\":\"268\",\"height\":\"70\",\"begin\":\"1.3\",\"end\":\"5.6\",\"isRecite\":\"0\",\"translate\":\"第1单元   你好！\",\"text\":\"unit one hello\"}", "{\"group\":0,\"left\":87,\"top\":188.60000000000002,\"width\":\"386\",\"height\":\"54\",\"begin\":\"5.6\",\"end\":\"11.5\",\"isRecite\":\"0\",\"translate\":\"A.让我们听一听、说一说\",\"text\":\"Part A,let's listen and say\"}",
            "{\"group\":0,\"left\":95,\"top\":339.6,\"width\":\"187\",\"height\":\"36\",\"begin\":\"11.5\",\"end\":\"15.1\",\"isRecite\":\"0\",\"translate\":\"你好，我是明明。\",\"text\":\"hello,i'm mingming\"}", "{\"group\":0,\"left\":325,\"top\":329.6,\"width\":\"161\",\"height\":\"28\",\"begin\":\"15.1\",\"end\":\"18.4\",\"isRecite\":\"0\",\"translate\":\"你好，我是安妮。\",\"text\":\"hello i'm Anne\"}",
            "{\"group\":0,\"left\":549,\"top\":460.6,\"width\":\"122\",\"height\":\"34\",\"begin\":\"18.4\",\"end\":\"21.8\",\"isRecite\":\"0\",\"translate\":\"嗨，我是彼得。\",\"text\":\"hi,i'm peter\"}", "{\"group\":0,\"left\":254,\"top\":646.5999999999999,\"width\":\"165\",\"height\":\"30\",\"begin\":\"21.8\",\"end\":\"24.3\",\"isRecite\":\"0\",\"translate\":\"你好，我是玲玲。\",\"text\":\"hello,i'm lingling\"}"};
    private String[] jsonArr2 = {"{\"group\":1,\"left\":77,\"top\":79.60000000000002,\"width\":\"232\",\"height\":\"44\",\"begin\":\"27.0\",\"end\":\"31.8\",\"isRecite\":\"0\",\"translate\":\"B.让我们学一学\",\"text\":\"part B,let's learn\"}", "{\"group\":1,\"left\":140,\"top\":153.60000000000002,\"width\":\"182.4\",\"height\":\"28.4\",\"begin\":\"31.8\",\"end\":\"35.6\",\"isRecite\":\"0\",\"translate\":\"你好，我是明明。\",\"text\":\"hello,i'm mingming\"}",
            "{\"group\":1,\"left\":366,\"top\":164.60000000000002,\"width\":\"143\",\"height\":\"31\",\"begin\":\"35.6\",\"end\":\"40.8\",\"isRecite\":\"0\",\"translate\":\"嗨，我是玲玲。\",\"text\":\"hi,i'm lingling\"}", "{\"group\":1,\"left\":76,\"top\":387.6,\"width\":\"205\",\"height\":\"50\",\"begin\":\"40.8\",\"end\":\"45.8\",\"isRecite\":\"0\",\"translate\":\"C.让我们演一演\",\"text\":\"part C,let's act\"}",
            "{\"group\":1,\"left\":196,\"top\":464.6,\"width\":\"160\",\"height\":\"34\",\"begin\":\"45.8\",\"end\":\"49.4\",\"isRecite\":\"0\",\"translate\":\"你好，我是李老师。\",\"text\":\"hello,i'm miss li\"}", "{\"group\":1,\"left\":367,\"top\":564.6,\"width\":\"126\",\"height\":\"33\",\"begin\":\"49.4\",\"end\":\"53.4\",\"isRecite\":\"0\",\"translate\":\"你好，李老师。\",\"text\":\"hello,miss li\"}",
            "{\"group\":1,\"left\":179,\"top\":778.5999999999999,\"width\":\"129\",\"height\":\"32\",\"begin\":\"53.4\",\"end\":\"56.3\",\"isRecite\":\"0\",\"translate\":\"嗨，我是班尼。\",\"text\":\"hi,i'm benny\"}", "{\"group\":1,\"left\":417,\"top\":789.5999999999999,\"width\":\"124.4\",\"height\":\"32.4\",\"begin\":\"56.3\",\"end\":\"58.3\",\"isRecite\":\"0\",\"translate\":\"嗨，我是琳达。\",\"text\":\"hi,i'm linda\"}"};
    private int[] bgResIds = /*{R.drawable.langbei_1, R.drawable.langbei_2}*/{};
    private boolean completeExam = false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_mixed_exam);

        ScreenManager sm = new ScreenManager();
        if(!sm.setDeepStatusBar(true,this)){
            findViewById(R.id.titlebar_divider).setVisibility(View.GONE);
        }

        exercisePaperBean = (MutiExercisePaperBean) Session.getSession().get("examPaperBean");
        examType = getIntent().getIntExtra("examType", 0);
        jumpType = getIntent().getIntExtra(Constants.SCORE_RESULT_JUMP_TYPE, 0);
        subjectId = getIntent().getIntExtra("subjectId", 0);
        videoId = getIntent().getIntExtra("videoId", 0);

        initView();
        if (exercisePaperBean != null) {
            setData(exercisePaperBean);
        } else {
            getData();
        }

        DownloadUtil.getInstance().setOnDownloadFinishedListener(this);
        DownloadUtil.getInstance().setOnSourceExistListener(this);

        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        wakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, "KeepScreenOn");
        wakeLock.acquire();
    }

    private void initView() {
        viewPager = findViewById(R.id.exam_vp);
        examTimeTextView = findViewById(R.id.exam_title_tv);
        examTimeTextView.setText(ToolUtils.getExerciseTypeNameByTypeId(examType));
        tvTopicTotalNum = findViewById(R.id.tv_topic_total_num);
        tvCurrentNum = findViewById(R.id.tv_current_num);
        examButton = findViewById(R.id.exam_title_img);
        examButton.setOnClickListener(this);
        btnNextTopic = findViewById(R.id.btn_next_topic);
        btnNextTopic.setOnClickListener(this);
        rlVpContainer = findViewById(R.id.rl_vp_container);
        ivRight = findViewById(R.id.iv_right);
        ivWrong = findViewById(R.id.iv_wrong);

        if (jumpType == Constants.JUMP_TYPE_WRONG_TOPIC_WATCH || jumpType == Constants.JUMP_TYPE_TOPICS_WATCH) {
            viewPager.setScroll(true);
            btnNextTopic.setEnabled(true);
        }
        viewPager.addOnPageChangeListener(this);
        soundPool = new SoundPool.Builder().setMaxStreams(soundResIds.length).build();
        soundIdMap.put(0, soundPool.load(this, soundResIds[0], 1));
        soundIdMap.put(1, soundPool.load(this, soundResIds[1], 1));
        initAnswerAnimation();
        alreadyScoreReceiver = new AlreadyScoreReceiver();
    }

    private void initAnswerAnimation() {
        if (rightAnimation == null) {
            rightAnimation = new AnimationsContainer(R.array.loading_anim_right, 18).createProgressDialogAnim(ivRight);
            ivRight.clearAnimation();
        }

        if (wrongAnimation == null) {
            wrongAnimation = new AnimationsContainer(R.array.loading_anim_wrong, 18).createProgressDialogAnim(ivWrong);
            ivWrong.clearAnimation();
        }
    }

    private void getData() {
        if (examType != 0) {
            switch (examType) {
                case Constants.TYPE_SMART_EXERCISE://智能练习
                    getSmartExamData();
                    break;
                case Constants.TYPE_SYNC_EXERCISE://同步练习
                case Constants.TYPE_STRANGE_WORDS_EXERCISE://生字练习
                case Constants.TYPE_SPEAKING_EXERCISE://口语练习
                case Constants.TYPE_ENGLISH_WORDS_EXERCISE://单词练习
                case Constants.TYPE_HEARING_EXERCISE://听力练习
                case Constants.TYPE_CHINESE_SECT_EXERCISE://语文分科练习
                case Constants.TYPE_MACH_SECT_EXERCISE://数学分科练习
                case Constants.TYPE_ENGLISH_SECT_EXERCISE://英语分科练习
                    getMutipleExamData();
                    break;
                case Constants.TYPE_LEARN_BY_DO://边学边练
                    getLearnByDoExamData();
                    break;
                default:
                    break;
            }
        }
    }

    private void getLearnByDoExamData() {
        int childId = shuShanApplication.getCurrentChildId();
        UrlParse urlParse = new UrlCommParse(this, UrlConst.BASE_URL).appendRegion(UrlConst.GET_LEARN_BY_PAPER_NEW);
        UrlParse paramParse = new UrlCommParse(this)
                .putValue("child_id", childId)
                .putValue("subject_id", subjectId)
                .putValue("video_id", videoId);
        showWaitDialog();
        NetHelper.create()
                .url(urlParse.toStringOnlyHeader())
                .param(paramParse.toStringOnlyParam())
                .request(RequestType.REQUEST_TYPE_POST, new NetSingleCommListener<MutiExercisePaperBean>() {

                    @Override
                    protected void onCommon() {
                        dismissWaitDialog();
                    }

                    @Override
                    protected void onSuccess(MutiExercisePaperBean mutiExercisePaperBean) {
                        if (mutiExercisePaperBean == null) {
                            return;
                        }

                        exercisePaperBean = mutiExercisePaperBean;
                        setData(mutiExercisePaperBean);
                    }

                    @Override
                    protected void onError(CallbackCode errorCode, NetRetBean netRetBean) {
                        showNetError(netRetBean);
                    }
                });
    }

    private void setData(MutiExercisePaperBean paperBean) {
        if (jumpType == Constants.JUMP_TYPE_EXAM_REPEAT) {
            setRepeatExam(paperBean);
        }
        chineseExerciseBeans = paperBean.getChineseExerciseBeans();
        mathExerciseBeans = paperBean.getMathExerciseBeans();
        englishExerciseBeans = paperBean.getEnglishExerciseBeans();
        paperExerciseBeans = paperBean.getPaperBeans();

        setData();

        if(jumpType == Constants.JUMP_TYPE_EXAM_CONTINUE){
            jumpNoRecord();
        }
    }

    private void setRepeatExam(MutiExercisePaperBean examPaperBean) {
        if (examPaperBean == null) {
            return;
        }

        ToolUtils.clearRecord(examPaperBean);
    }

    private void setData() {
        List<Fragment> examFragments = new ArrayList<>();
        boolean isOnlyDisplay = false;
        if (jumpType == Constants.JUMP_TYPE_WRONG_TOPIC_WATCH || jumpType == Constants.JUMP_TYPE_TOPICS_WATCH) {
            isOnlyDisplay = true;
        }
        if (examType != 0) {
            switch (examType) {
                case Constants.TYPE_STRANGE_WORDS_EXERCISE://生字练习
                    if (ToolUtils.isListEmpty(chineseExerciseBeans)) {
                        break;
                    }
                    examFragments = getStrangeWordsExamFragments(isOnlyDisplay);
                    downloadStrangeWordsAudio(false);
                    break;
                case Constants.TYPE_SPEAKING_EXERCISE://口语练习
                    if (ToolUtils.isListEmpty(englishExerciseBeans)) {
                        break;
                    }
                    examFragments = getSpeakingExamFragments(isOnlyDisplay);
                    downloadSpeakingExamAudio(false);
                    break;
                case Constants.TYPE_ENGLISH_WORDS_EXERCISE://单词练习
                    if (ToolUtils.isListEmpty(englishExerciseBeans)) {
                        break;
                    }
                    examFragments = getEnglishWordsExamFragments(isOnlyDisplay);
                    downloadEnglishWordsAudio(false);
                    break;
                case Constants.TYPE_HEARING_EXERCISE://听力练习
                    if (ToolUtils.isListEmpty(englishExerciseBeans)) {
                        break;
                    }
                    examFragments = getHearingExamFragments(isOnlyDisplay);
                    downloadHearingExamAudio(false);
                    break;
                case Constants.TYPE_SYNC_EXERCISE://同步练习
                case Constants.TYPE_CHINESE_SECT_EXERCISE://语文分科练习
                case Constants.TYPE_MACH_SECT_EXERCISE://数学分科练习
                case Constants.TYPE_ENGLISH_SECT_EXERCISE://英语分科练习
                case Constants.TYPE_SMART_EXERCISE://智能练习
                case Constants.TYPE_LEARN_BY_DO://边学边练
                    examFragments = getSyncExamFragments(isOnlyDisplay);
                    break;
            }
        }
        if (ToolUtils.isListEmpty(examFragments)) {
            showToast("题目信息为空，请重试");
            return;
        }
        tvTopicTotalNum.setText("/" + examFragments.size() + ")");
        examFragmentAdapter = new ExamFragmentAdapter(this, getSupportFragmentManager(), examFragments);
        viewPager.setAdapter(examFragmentAdapter);

        showCollect();
        playAudio();
    }

    @Override
    public void onDownloadFinished() {
        playAudio();
    }

    @Override
    public void onSourceExist() {
        playAudio();
    }

    private List<Fragment> getSyncExamFragments(boolean isOnlyDisplay) {
        List<Fragment> fragments = new ArrayList<>();
        if (examType == Constants.TYPE_LEARN_BY_DO) {
            fragments.addAll(getExamFragments(isOnlyDisplay, 0, paperExerciseBeans));
            downloadAllExamAudio();
        }else if (examType == Constants.TYPE_SMART_EXERCISE){
            fragments.addAll(getExamFragments(isOnlyDisplay, 0, paperExerciseBeans));
            downloadMutiExamAudio();
        } else {
            fragments.addAll(getExamFragments(isOnlyDisplay, 0, chineseExerciseBeans));
            fragments.addAll(getExamFragments(isOnlyDisplay, fragments.size(), mathExerciseBeans));
            fragments.addAll(getExamFragments(isOnlyDisplay, fragments.size(), englishExerciseBeans));
            downloadMutiExamAudio();
        }
        return fragments;
    }

    private void downloadAllExamAudio() {
        List<String[]> downloadInfos = new ArrayList<>();
        for (int i = 0; i < paperExerciseBeans.size(); i++) {
            MutiExerciseBean exerciseBean = paperExerciseBeans.get(i);
            if (TextUtils.isEmpty(exerciseBean.voice)) {
                continue;
            }
            switch (Integer.parseInt(exerciseBean.exercises_type)) {
                case Constants.TYPE_STRANGE_WORDS_EXERCISE://生字练习
                    if (exerciseBean.exercises_level.equals("1")) {//生字练习题型2
                        String[] strings = {DownloadUtil.getStrangeWordsExamAudioPath(exerciseBean), BuildConfig.wxUpImgBaseUrl + exerciseBean.voice};
                        downloadInfos.add(strings);
                    }
                    break;
                case Constants.TYPE_SPEAKING_EXERCISE://口语练习
                    String[] strs = {DownloadUtil.getSpeakingExamAudioPath(exerciseBean.outline_detail_id, exerciseBean.id), BuildConfig.wxUpImgBaseUrl + exerciseBean.voice};
                    downloadInfos.add(strs);
                    break;
                case Constants.TYPE_ENGLISH_WORDS_EXERCISE://单词练习
                    if (!exerciseBean.exercises_level.equals("1")) {//除了题型2都有音频需要下载
                        String[] strs2 = {DownloadUtil.getEnglishWordsStudyAudioPath(exerciseBean.outline_detail_id, exerciseBean.id), BuildConfig.wxUpImgBaseUrl + exerciseBean.voice};
                        downloadInfos.add(strs2);
                    }
                    break;
                case Constants.TYPE_HEARING_EXERCISE://听力练习
                    String[] strs3 = {DownloadUtil.getHearingExamAudioPath(exerciseBean.outline_detail_id, exerciseBean.id), BuildConfig.wxUpImgBaseUrl + exerciseBean.voice};
                    downloadInfos.add(strs3);
                    break;
            }
        }
        DownloadUtil.getInstance().createAllTypeExamDownloadDir();
        DownloadUtil.getInstance().downloadData(this, downloadInfos);
    }

    private void downloadMutiExamAudio() {
        List<String[]> downloadInfos = new ArrayList<>();
        downloadInfos.addAll(downloadEnglishWordsAudio(true));
        downloadInfos.addAll(downloadHearingExamAudio(true));
        downloadInfos.addAll(downloadSpeakingExamAudio(true));
        downloadInfos.addAll(downloadStrangeWordsAudio(true));

        DownloadUtil.getInstance().downloadData(this, downloadInfos);
    }

    private List<Fragment> getExamFragments(boolean isOnlyDisplay, int beginIndex, List<MutiExerciseBean> exerciseBeans) {
        int startIndex = 0;
        int wrongTopicStartIndex = 0;
        List<Fragment> fragments = new ArrayList<>();
        if (!ToolUtils.isListEmpty(exerciseBeans)) {
            for (int i = 0; i < exerciseBeans.size(); i++) {
                MutiExerciseBean exerciseBean = exerciseBeans.get(i);
                switch (Integer.parseInt(exerciseBean.exercises_type)) {
                    case Constants.TYPE_SYNC_EXERCISE://同步练习
                    case Constants.TYPE_CHINESE_SECT_EXERCISE://语文分科练习
                    case Constants.TYPE_MACH_SECT_EXERCISE://数学分科练习
                    case Constants.TYPE_ENGLISH_SECT_EXERCISE://英语分科练习
                        if (exerciseBean.exercises_level.equals("0")) {//单选题
                            if (jumpType == Constants.JUMP_TYPE_WRONG_TOPIC_WATCH) {
                                if (ToolUtils.isWrongTopic(Integer.parseInt(exerciseBean.exercises_level), exerciseBean)) {
                                    ExamFragment syncFragment = ExamFragment.newInstance(isOnlyDisplay, beginIndex + wrongTopicStartIndex + i, exerciseBean);
                                    syncFragment.setOnAnswerSelectListener(this);
                                    fragments.add(syncFragment);
                                    wrongTopicStartIndex++;
                                }
                            } else {
                                ExamFragment syncFragment = ExamFragment.newInstance(isOnlyDisplay, beginIndex + startIndex + i, exerciseBean);
                                syncFragment.setOnAnswerSelectListener(this);
                                fragments.add(syncFragment);
                            }
                        } else if (exerciseBean.exercises_level.equals("1")) {//填空题
                            if (jumpType == Constants.JUMP_TYPE_WRONG_TOPIC_WATCH) {
                                if (ToolUtils.isWrongTopic(Integer.parseInt(exerciseBean.exercises_level), exerciseBean)) {
                                    FillBlankExamFragment blankFragment = FillBlankExamFragment.newInstance(isOnlyDisplay, beginIndex + wrongTopicStartIndex + i, exerciseBean);
                                    blankFragment.setOnAnswerSelectListener(this);
                                    fragments.add(blankFragment);
                                    wrongTopicStartIndex++;
                                }
                            } else {
                                FillBlankExamFragment blankFragment = FillBlankExamFragment.newInstance(isOnlyDisplay, beginIndex + startIndex + i, exerciseBean);
                                blankFragment.setOnAnswerSelectListener(this);
                                fragments.add(blankFragment);
                            }
                        }
                        startIndex++;
                        break;
                    case Constants.TYPE_STRANGE_WORDS_EXERCISE://生字练习
                        if (exerciseBean.exercises_level.equals("1")) {//生字题型2
                            if (jumpType == Constants.JUMP_TYPE_WRONG_TOPIC_WATCH) {
                                if (ToolUtils.isWrongTopic(Integer.parseInt(exerciseBean.exercises_level), exerciseBean)) {
                                    StrangeWordsExam2Fragment exam2Fragment = StrangeWordsExam2Fragment.newInstance(isOnlyDisplay, beginIndex + wrongTopicStartIndex + i, DownloadUtil.getStrangeWordsExamAudioPath(exerciseBean), exerciseBean);
                                    exam2Fragment.setOnAnswerSelectListener(this);
                                    fragments.add(exam2Fragment);
                                    wrongTopicStartIndex++;
                                }
                            } else {
                                StrangeWordsExam2Fragment exam2Fragment = StrangeWordsExam2Fragment.newInstance(isOnlyDisplay, beginIndex + startIndex + i, DownloadUtil.getStrangeWordsExamAudioPath(exerciseBean), exerciseBean);
                                exam2Fragment.setOnAnswerSelectListener(this);
                                fragments.add(exam2Fragment);
                            }
                        } else if (exerciseBean.exercises_level.equals("0")) {//生字题型1
                            if (jumpType == Constants.JUMP_TYPE_WRONG_TOPIC_WATCH) {
                                if (ToolUtils.isWrongTopic(Integer.parseInt(exerciseBean.exercises_level), exerciseBean)) {
                                    StrangeWordsExamFragment examFragment = StrangeWordsExamFragment.newInstance(isOnlyDisplay, beginIndex + wrongTopicStartIndex + i, exerciseBean);
                                    examFragment.setOnAnswerSelectListener(this);
                                    fragments.add(examFragment);
                                    wrongTopicStartIndex++;
                                }
                            } else {
                                StrangeWordsExamFragment examFragment = StrangeWordsExamFragment.newInstance(isOnlyDisplay, beginIndex + startIndex + i, exerciseBean);
                                examFragment.setOnAnswerSelectListener(this);
                                fragments.add(examFragment);
                            }
                        }
                        startIndex++;
                        break;
                    case Constants.TYPE_SPEAKING_EXERCISE://口语练习
                        if (jumpType == Constants.JUMP_TYPE_WRONG_TOPIC_WATCH) {
                            if (ToolUtils.isWrongTopic(Integer.parseInt(exerciseBean.exercises_level), exerciseBean)) {
                                SpeakingExamFragment examFragment = SpeakingExamFragment.newInstance(isOnlyDisplay, beginIndex + wrongTopicStartIndex + i, exerciseBean);
                                examFragment.setOnAnswerSelectListener(this);
                                fragments.add(examFragment);
                                wrongTopicStartIndex++;
                            }
                        } else {
                            SpeakingExamFragment examFragment = SpeakingExamFragment.newInstance(isOnlyDisplay, beginIndex + startIndex + i, exerciseBean);
                            examFragment.setOnAnswerSelectListener(this);
                            fragments.add(examFragment);
                        }
                        startIndex++;
                        break;
                    case Constants.TYPE_ENGLISH_WORDS_EXERCISE://单词练习
                        switch (Integer.parseInt(exerciseBean.exercises_level)) {
                            case 0://题型1
                            case 1://题型2
                            case 3://题型4
                                if (jumpType == Constants.JUMP_TYPE_WRONG_TOPIC_WATCH) {
                                    if (ToolUtils.isWrongTopic(Integer.parseInt(exerciseBean.exercises_level), exerciseBean)) {
                                        EnglishWordsExamFragment fragment124 = EnglishWordsExamFragment.newInstance(isOnlyDisplay, beginIndex + wrongTopicStartIndex + i, exerciseBean);
                                        fragment124.setOnAnswerSelectListener(this);
                                        fragments.add(fragment124);
                                        wrongTopicStartIndex++;
                                    }
                                } else {
                                    EnglishWordsExamFragment fragment124 = EnglishWordsExamFragment.newInstance(isOnlyDisplay, beginIndex + startIndex + i, exerciseBean);
                                    fragment124.setOnAnswerSelectListener(this);
                                    fragments.add(fragment124);
                                }
                                break;
                            case 2://题型3
                                if (jumpType == Constants.JUMP_TYPE_WRONG_TOPIC_WATCH) {
                                    if (ToolUtils.isWrongTopic(Integer.parseInt(exerciseBean.exercises_level), exerciseBean)) {
                                        EnglishWordsExam3Fragment fragment3 = EnglishWordsExam3Fragment.newInstance(this, isOnlyDisplay, beginIndex + wrongTopicStartIndex + i, exerciseBean);
                                        fragment3.setOnAnswerSelectListener(this);
                                        fragments.add(fragment3);
                                        wrongTopicStartIndex++;
                                    }
                                } else {
                                    EnglishWordsExam3Fragment fragment3 = EnglishWordsExam3Fragment.newInstance(this, isOnlyDisplay, beginIndex + startIndex + i, exerciseBean);
                                    fragment3.setOnAnswerSelectListener(this);
                                    fragments.add(fragment3);
                                }
                                break;
                        }
                        startIndex++;
                        break;
                    case Constants.TYPE_HEARING_EXERCISE://听力练习
                        if (jumpType == Constants.JUMP_TYPE_WRONG_TOPIC_WATCH) {
                            if (ToolUtils.isWrongTopic(Integer.parseInt(exerciseBean.exercises_level), exerciseBean)) {
                                HearingExamFragment hearingFragment = HearingExamFragment.newInstance(isOnlyDisplay, beginIndex + wrongTopicStartIndex + i, exerciseBean);
                                hearingFragment.setOnAnswerSelectListener(this);
                                fragments.add(hearingFragment);
                                wrongTopicStartIndex++;
                            }
                        } else {
                            HearingExamFragment hearingFragment = HearingExamFragment.newInstance(isOnlyDisplay, beginIndex + startIndex + i, exerciseBean);
                            hearingFragment.setOnAnswerSelectListener(this);
                            fragments.add(hearingFragment);
                        }
                        startIndex++;
                        break;
                    default:
                        break;
                }
            }
        }
        return fragments;
    }

    private List<String[]> downloadHearingExamAudio(boolean isForMutiExam) {
        List<String[]> downloadInfos = new ArrayList<>();
        for (int i = 0; i < englishExerciseBeans.size(); i++) {
            MutiExerciseBean exerciseBean = englishExerciseBeans.get(i);
            if (TextUtils.isEmpty(exerciseBean.voice)) {
                continue;
            }
            String[] strs = {DownloadUtil.getHearingExamAudioPath(exerciseBean.outline_detail_id, exerciseBean.id), BuildConfig.wxUpImgBaseUrl + exerciseBean.voice};
            downloadInfos.add(strs);
        }
        DownloadUtil.getInstance().createHearingExamDownloadDir();
        if (!isForMutiExam) {
            DownloadUtil.getInstance().downloadData(this, downloadInfos);
        }
        return downloadInfos;
    }

    private List<String[]> downloadSpeakingExamAudio(boolean isForMutiExam) {
        List<String[]> downloadInfos = new ArrayList<>();
        for (int i = 0; i < englishExerciseBeans.size(); i++) {
            MutiExerciseBean exerciseBean = englishExerciseBeans.get(i);
            if (TextUtils.isEmpty(exerciseBean.voice)) {
                continue;
            }
            String[] strs = {DownloadUtil.getSpeakingExamAudioPath(exerciseBean.outline_detail_id, exerciseBean.id), BuildConfig.wxUpImgBaseUrl + exerciseBean.voice};
            downloadInfos.add(strs);
        }
        DownloadUtil.getInstance().createSpeakingExamDownloadDir();
        if (!isForMutiExam) {
            DownloadUtil.getInstance().downloadData(this, downloadInfos);
        }
        return downloadInfos;
    }

    private List<String[]> downloadEnglishWordsAudio(boolean isForMutiExam) {
        List<String[]> downloadInfos = new ArrayList<>();
        for (int i = 0; i < englishExerciseBeans.size(); i++) {
            MutiExerciseBean exerciseBean = englishExerciseBeans.get(i);
            if (TextUtils.isEmpty(exerciseBean.voice)) {
                continue;
            }
            if (!exerciseBean.exercises_level.equals("1")) {//除了题型2都有音频需要下载
                String[] strs = {DownloadUtil.getEnglishWordsStudyAudioPath(exerciseBean.outline_detail_id,
                        exerciseBean.id), BuildConfig.wxUpImgBaseUrl + exerciseBean.voice};
                downloadInfos.add(strs);
            }
        }
        DownloadUtil.getInstance().createEnglishWordsDownloadDir();
        if (!isForMutiExam) {
            DownloadUtil.getInstance().downloadData(this, downloadInfos);
        }
        return downloadInfos;
    }

    private List<String[]> downloadStrangeWordsAudio(boolean isForMutiExam) {
        List<String[]> downloadInfos = new ArrayList<>();
        for (int i = 0; i < chineseExerciseBeans.size(); i++) {
            MutiExerciseBean exerciseBean = chineseExerciseBeans.get(i);
            if (TextUtils.isEmpty(exerciseBean.voice)) {
                continue;
            }
            if (exerciseBean.exercises_level.equals("1")) {//生字练习题型2
                String[] strings = {DownloadUtil.getStrangeWordsExamAudioPath(exerciseBean), BuildConfig.wxUpImgBaseUrl + exerciseBean.voice};
                downloadInfos.add(strings);
            }
        }
        DownloadUtil.getInstance().createStrangeWordsDownloadDir();
        if (!isForMutiExam) {
            DownloadUtil.getInstance().downloadData(this, downloadInfos);
        }
        return downloadInfos;
    }

    private void getSmartExamData() {
        int childId = shuShanApplication.getCurrentChildId();
        UrlParse urlParse = new UrlCommParse(this, UrlConst.BASE_URL).appendRegion(UrlConst.SMART_TYPES_EXAM);
        UrlParse paramParse = new UrlCommParse(this)
                .putValue("child_id", childId)
                .putValue("practice_type", examType);
        showWaitDialog();
        NetHelper.create()
                .url(urlParse.toStringOnlyHeader())
                .param(paramParse.toStringOnlyParam())
                .request(RequestType.REQUEST_TYPE_POST, new NetSingleCommListener<MutiExercisePaperBean>() {
                    @Override
                    protected void onCommon() {
                        dismissWaitDialog();
                    }

                    @Override
                    protected void onSuccess(MutiExercisePaperBean mutiExercisePaperBean) {
                        if (mutiExercisePaperBean == null) {
                            return;
                        }
                        exercisePaperBean = mutiExercisePaperBean;
                        chineseExerciseBeans = mutiExercisePaperBean.getChineseExerciseBeans();
                        mathExerciseBeans = mutiExercisePaperBean.getMathExerciseBeans();
                        englishExerciseBeans = mutiExercisePaperBean.getEnglishExerciseBeans();
                        paperExerciseBeans = mutiExercisePaperBean.getPaperBeans();

                        setData();
                    }

                    @Override
                    protected void onError(CallbackCode errorCode, NetRetBean netRetBean) {
                        showNetError(netRetBean);
                    }
                });
    }

    private void getMutipleExamData() {
        int childId = shuShanApplication.getCurrentChildId();
        UrlParse urlParse = new UrlCommParse(this, UrlConst.BASE_URL).appendRegion(UrlConst.MUTIPLE_TYPES_EXAM);
        UrlParse paramParse = new UrlCommParse(this)
                .putValue("child_id", childId)
                .putValue("practice_type", examType);
        showWaitDialog();
        NetHelper.create()
                .url(urlParse.toStringOnlyHeader())
                .param(paramParse.toStringOnlyParam())
                .request(RequestType.REQUEST_TYPE_POST, new NetSingleCommListener<MutiExercisePaperBean>() {
                    @Override
                    protected void onCommon() {
                        dismissWaitDialog();
                    }

                    @Override
                    protected void onSuccess(MutiExercisePaperBean mutiExercisePaperBean) {
                        if (mutiExercisePaperBean == null) {
                            return;
                        }
                        exercisePaperBean = mutiExercisePaperBean;
                        chineseExerciseBeans = mutiExercisePaperBean.getChineseExerciseBeans();
                        mathExerciseBeans = mutiExercisePaperBean.getMathExerciseBeans();
                        englishExerciseBeans = mutiExercisePaperBean.getEnglishExerciseBeans();

                        setData();
                    }

                    @Override
                    protected void onError(CallbackCode errorCode, NetRetBean netRetBean) {
                        showNetError(netRetBean);
                    }
                });
    }

    private List<Fragment> getStrangeWordsExamFragments(boolean isOnlyDisplay) {
        int wrongTopicNum = 0;
        List<Fragment> examFragments = new ArrayList<>();
        for (int i = 0; i < chineseExerciseBeans.size(); i++) {
            MutiExerciseBean exerciseBean = chineseExerciseBeans.get(i);
            if (exerciseBean.exercises_level.equals("1")) {//生字题型2
                if (jumpType == Constants.JUMP_TYPE_WRONG_TOPIC_WATCH) {
                    if (ToolUtils.isWrongTopic(Integer.parseInt(exerciseBean.exercises_level), exerciseBean)) {
                        StrangeWordsExam2Fragment exam2Fragment = StrangeWordsExam2Fragment.newInstance(isOnlyDisplay, wrongTopicNum++, DownloadUtil.getStrangeWordsExamAudioPath(exerciseBean), exerciseBean);
                        exam2Fragment.setOnAnswerSelectListener(this);
                        examFragments.add(exam2Fragment);
                    }
                } else {
                    StrangeWordsExam2Fragment exam2Fragment = StrangeWordsExam2Fragment.newInstance(isOnlyDisplay, i, DownloadUtil.getStrangeWordsExamAudioPath(exerciseBean), exerciseBean);
                    exam2Fragment.setOnAnswerSelectListener(this);
                    examFragments.add(exam2Fragment);
                }
            } else if (exerciseBean.exercises_level.equals("0")) {//生字题型1
                if (jumpType == Constants.JUMP_TYPE_WRONG_TOPIC_WATCH) {
                    if (ToolUtils.isWrongTopic(Integer.parseInt(exerciseBean.exercises_level), exerciseBean)) {
                        StrangeWordsExamFragment examFragment = StrangeWordsExamFragment.newInstance(isOnlyDisplay, wrongTopicNum++, exerciseBean);
                        examFragment.setOnAnswerSelectListener(this);
                        examFragments.add(examFragment);
                    }
                } else {
                    StrangeWordsExamFragment examFragment = StrangeWordsExamFragment.newInstance(isOnlyDisplay, i, exerciseBean);
                    examFragment.setOnAnswerSelectListener(this);
                    examFragments.add(examFragment);
                }
            }
        }
        return examFragments;
    }

    private List<Fragment> getSpeakingExamFragments(boolean isOnlyDisplay) {
        int wrongTopicNum = 0;
        List<Fragment> examFragments = new ArrayList<>();
        for (int i = 0; i < englishExerciseBeans.size(); i++) {
            MutiExerciseBean exerciseBean = englishExerciseBeans.get(i);
            if (jumpType == Constants.JUMP_TYPE_WRONG_TOPIC_WATCH) {
                if (ToolUtils.isWrongTopic(Integer.parseInt(exerciseBean.exercises_level), exerciseBean)) {
                    SpeakingExamFragment examFragment = SpeakingExamFragment.newInstance(isOnlyDisplay, wrongTopicNum++, exerciseBean);
                    examFragment.setOnAnswerSelectListener(this);
                    examFragments.add(examFragment);
                }
            } else {
                SpeakingExamFragment examFragment = SpeakingExamFragment.newInstance(isOnlyDisplay, i, exerciseBean);
                examFragment.setOnAnswerSelectListener(this);
                examFragments.add(examFragment);
            }
        }
        return examFragments;
    }

    private List<Fragment> getHearingExamFragments(boolean isOnlyDisplay) {
        int wrongTopicNum = 0;
        List<Fragment> fragments = new ArrayList<>();
        for (int i = 0; i < englishExerciseBeans.size(); i++) {
            MutiExerciseBean exerciseBean = englishExerciseBeans.get(i);
            if (jumpType == Constants.JUMP_TYPE_WRONG_TOPIC_WATCH) {
                if (ToolUtils.isWrongTopic(Integer.parseInt(exerciseBean.exercises_level), exerciseBean)) {
                    HearingExamFragment examFragment = HearingExamFragment.newInstance(isOnlyDisplay, wrongTopicNum++, exerciseBean);
                    examFragment.setOnAnswerSelectListener(this);
                    fragments.add(examFragment);
                }
            } else {
                HearingExamFragment examFragment = HearingExamFragment.newInstance(isOnlyDisplay, i, exerciseBean);
                examFragment.setOnAnswerSelectListener(this);
                fragments.add(examFragment);
            }
        }
        return fragments;
    }

    private List<Fragment> getEnglishWordsExamFragments(boolean isOnlyDisplay) {
        int wrongTopicNum = 0;
        List<Fragment> fragments = new ArrayList<>();
        for (int i = 0; i < englishExerciseBeans.size(); i++) {
            MutiExerciseBean exerciseBean = englishExerciseBeans.get(i);
            switch (Integer.parseInt(exerciseBean.exercises_level)) {
                case 0://题型1
                case 1://题型2
                case 3://题型4
                    if (jumpType == Constants.JUMP_TYPE_WRONG_TOPIC_WATCH) {
                        if (ToolUtils.isWrongTopic(Integer.parseInt(exerciseBean.exercises_level), exerciseBean)) {
                            EnglishWordsExamFragment fragment124 = EnglishWordsExamFragment.newInstance(isOnlyDisplay, wrongTopicNum++, exerciseBean);
                            fragment124.setOnAnswerSelectListener(this);
                            fragments.add(fragment124);
                        }
                    } else {
                        EnglishWordsExamFragment fragment124 = EnglishWordsExamFragment.newInstance(isOnlyDisplay, i, exerciseBean);
                        fragment124.setOnAnswerSelectListener(this);
                        fragments.add(fragment124);
                    }
                    break;
                case 2://题型3
                    if (jumpType == Constants.JUMP_TYPE_WRONG_TOPIC_WATCH) {
                        if (ToolUtils.isWrongTopic(Integer.parseInt(exerciseBean.exercises_level), exerciseBean)) {
                            EnglishWordsExam3Fragment fragment3 = EnglishWordsExam3Fragment.newInstance(this, isOnlyDisplay, wrongTopicNum++, exerciseBean);
                            fragment3.setOnAnswerSelectListener(this);
                            fragments.add(fragment3);
                        }
                    } else {
                        EnglishWordsExam3Fragment fragment3 = EnglishWordsExam3Fragment.newInstance(this, isOnlyDisplay, i, exerciseBean);
                        fragment3.setOnAnswerSelectListener(this);
                        fragments.add(fragment3);
                    }
                    break;
            }
        }
        return fragments;
    }

    private List<Fragment> getReadReciteFragments() {
        List<Fragment> fragments = new ArrayList<>();
        try {
            List<ReadReciteDataBean> rrDataBean = new ArrayList<>();
            for (int i = 0; i < jsonArr.length; i++) {
                JSONObject jsonObject = new JSONObject(jsonArr[i]);
                ReadReciteDataBean dataBean = new ReadReciteDataBean();
                dataBean.initByJson(jsonObject);
                rrDataBean.add(dataBean);
            }
            fragments.add(ReadReciteExamFragment.newInstance(bgResIds[0], vpWidth, vpHeight, rrDataBean));

            List<ReadReciteDataBean> rrDataBean2 = new ArrayList<>();
            for (int i = 0; i < jsonArr2.length; i++) {
                JSONObject jsonObject = new JSONObject(jsonArr2[i]);
                ReadReciteDataBean dataBean = new ReadReciteDataBean();
                dataBean.initByJson(jsonObject);
                rrDataBean2.add(dataBean);
            }
            fragments.add(ReadReciteExamFragment.newInstance(bgResIds[1], vpWidth, vpHeight, rrDataBean2));
        } catch (JSONException je) {
            je.printStackTrace();
        } finally {
            return fragments;
        }
    }

    @Override
    public boolean onAnswerSelect(int examIndex, boolean isRight) {
        Log.i(TAG, "examIndex=" + examIndex + " isRight=" + isRight);

        btnNextTopic.setEnabled(true);
        if (isRight) {
            rightNum++;
        } else {
            wrongNum++;
        }

        if (isRight) {
            if(soundIdMap != null){
                soundPool.play(soundIdMap.get(0), 1, 1, 1, 0, 1);
                if (rightAnimation.isRunning()) {
                    rightAnimation.stop();
                }
                rightAnimation.start();
            }
        } else {
            if(soundIdMap != null){
                soundPool.play(soundIdMap.get(1), 1, 1, 1, 0, 1);
                if (wrongAnimation.isRunning()) {
                    wrongAnimation.stop();
                }
                wrongAnimation.start();
            }
        }
        return true;
    }

    public void enableNextBtn() {
        if (btnNextTopic != null) {
            btnNextTopic.setEnabled(true);
        }
    }

    private void postSmartRecord() {
        int childId = shuShanApplication.getCurrentChildId();
        UrlParse urlParse = new UrlCommParse(this, UrlConst.BASE_URL).appendRegion(UrlConst.SMART_EXAM_TOPIC_REPORT);
        UrlParse paramParse = new UrlCommParse(this)
                .putValue("answer", getAnswerJsonArr(false))
                .putValue("practice_type", 2)
                .putValue("child_id", childId)
                .putValue("paper_id", exercisePaperBean.paperInfoBean.id)
                .putValue("time_consuming", 30);
        showWaitDialog();
        NetHelper.create()
                .url(urlParse.toStringOnlyHeader())
                .param(paramParse.toStringOnlyParam())
                .request(RequestType.REQUEST_TYPE_POST, new NetSingleCommListener<ExerciseResultBean>() {

                    @Override
                    protected void onCommon() {
                        dismissWaitDialog();
                    }

                    @Override
                    protected void onSuccess(ExerciseResultBean exerciseResultBean) {
                        onBackAction();
                        if (exerciseResultBean == null) {
                            showToast("服务端数据返回为空");
                            return;
                        }
                        gotoScoreResult(exerciseResultBean);
                    }

                    @Override
                    protected void onError(CallbackCode errorCode, NetRetBean netRetBean) {
                        showNetError(netRetBean);
                    }
                });

    }

    private void postPaperRecord() {
        int childId = shuShanApplication.getCurrentChildId();
        UrlParse urlParse = new UrlCommParse(this, UrlConst.BASE_URL).appendRegion(UrlConst.MIXED_EXAM_TOPIC_REPORT);
        UrlParse paramParse = new UrlCommParse(this)
                .putValue("answer", getAnswerJsonArr(false))
                .putValue("exercises_type", examType)
                .putValue("child_id", childId)
                .putValue("paper_id", exercisePaperBean.paperInfoBean.id)
                .putValue("repeat", jumpType == Constants.JUMP_TYPE_EXAM_REPEAT ? 1 : 2)
                .putValue("time_consuming", 50)
                .putValue("video_id", 0)
                .putValue("special_id", 0);
        showWaitDialog();
        NetHelper.create()
                .url(urlParse.toStringOnlyHeader())
                .param(paramParse.toStringOnlyParam())
                .request(RequestType.REQUEST_TYPE_POST, new NetSingleCommListener<ExerciseResultBean>() {

                    @Override
                    protected void onCommon() {
                        dismissWaitDialog();
                    }

                    @Override
                    protected void onSuccess(ExerciseResultBean exerciseResultBean) {
                        onBackAction();
                        if (exerciseResultBean == null) {
                            showToast("服务端数据返回为空");
                            return;
                        }
                        gotoScoreResult(exerciseResultBean);
                    }

                    @Override
                    protected void onError(CallbackCode errorCode, NetRetBean netRetBean) {
                        showNetError(netRetBean);
                    }
                });

    }

    private void gotoScoreResult(ExerciseResultBean exerciseResultBean) {
        Session.getSession().put("exerciseResultBean", exerciseResultBean);
        Session.getSession().put("examPaperBean", exercisePaperBean);

        Intent intent = new Intent(this, MixedExamScoreActivity.class);
        intent.putExtra("examType", examType);
        intent.putExtra("subjectId", subjectId);
        startActivityAllow(intent);
    }

    private String getAnswerJsonArr(boolean isJumpContinue) {
        JSONArray jsonArr = new JSONArray();
        switch (examType) {
            case Constants.TYPE_STRANGE_WORDS_EXERCISE://生字练习
            case Constants.TYPE_CHINESE_SECT_EXERCISE://语文分科练习
                for (int i = 0; i < chineseExerciseBeans.size(); i++) {
                    jsonArr.put(getAnswerJson(isJumpContinue,i,chineseExerciseBeans.get(i)));
                }
                break;
            case Constants.TYPE_MACH_SECT_EXERCISE://数学分科练习
                for (int i = 0; i < mathExerciseBeans.size(); i++) {
                    jsonArr.put(getAnswerJson(isJumpContinue,i,mathExerciseBeans.get(i)));
                }
                break;
            case Constants.TYPE_SPEAKING_EXERCISE://口语练习
            case Constants.TYPE_ENGLISH_WORDS_EXERCISE://单词练习
            case Constants.TYPE_HEARING_EXERCISE://听力练习
            case Constants.TYPE_ENGLISH_SECT_EXERCISE://英语分科练习
                for (int i = 0; i < englishExerciseBeans.size(); i++) {
                    jsonArr.put(getAnswerJson(isJumpContinue,i,englishExerciseBeans.get(i)));
                }
                break;
            case Constants.TYPE_SYNC_EXERCISE://同步练习
            case Constants.TYPE_SMART_EXERCISE://智能练习
            case Constants.TYPE_LEARN_BY_DO://边学边练
                if (exercisePaperBean == null) {
                    break;
                }
                jsonArr = getAnswerJsonArr(isJumpContinue,exercisePaperBean);
                break;
        }
        return jsonArr.toString();
    }

    private JSONArray getAnswerJsonArr(boolean isJumpContinue,MutiExercisePaperBean exercisePaperBean) {
        JSONArray jsonArray = new JSONArray();
        if (examType == Constants.TYPE_SMART_EXERCISE || (videoId != 0 && subjectId != 0)) {
            List<MutiExerciseBean> exerciseBeans = exercisePaperBean.getPaperBeans();
            if (!ToolUtils.isListEmpty(exerciseBeans)) {
                for (int i = 0; i < exerciseBeans.size(); i++) {
                    jsonArray.put(getAnswerJson(isJumpContinue,i,exerciseBeans.get(i)));
                }
            }
        } else {
            List<MutiExerciseBean> chineseExerciseBeans = exercisePaperBean.getChineseExerciseBeans();
            if (!ToolUtils.isListEmpty(chineseExerciseBeans)) {
                for (int i = 0; i < chineseExerciseBeans.size(); i++) {
                    jsonArray.put(getAnswerJson(isJumpContinue,i,chineseExerciseBeans.get(i)));
                }
            }

            List<MutiExerciseBean> mathExerciseBeans = exercisePaperBean.getMathExerciseBeans();
            if (!ToolUtils.isListEmpty(mathExerciseBeans)) {
                for (int i = 0; i < mathExerciseBeans.size(); i++) {
                    jsonArray.put(getAnswerJson(isJumpContinue,i,mathExerciseBeans.get(i)));
                }
            }

            List<MutiExerciseBean> englishExerciseBeans = exercisePaperBean.getEnglishExerciseBeans();
            if (!ToolUtils.isListEmpty(englishExerciseBeans)) {
                for (int i = 0; i < englishExerciseBeans.size(); i++) {
                    jsonArray.put(getAnswerJson(isJumpContinue,i,englishExerciseBeans.get(i)));
                }
            }
        }
        return jsonArray;
    }

    private JSONObject getAnswerJson(boolean isJumpContinue,int beanndex,MutiExerciseBean exerciseBean) {
        JSONObject obj = new JSONObject();
        try {
            initSelectTopicArguments(exerciseBean);
            obj.put("id", exerciseBean.id);
            obj.put("exercises_type", exerciseBean.exercises_type);
            obj.put("exercises_level", exerciseBean.exercises_level);
            obj.put("outline_detail_id", exerciseBean.outline_detail_id);
            obj.put("score", exerciseBean.score);
            obj.put("subject_id", exerciseBean.subject_id);
            obj.put("outline_id", exerciseBean.outline_id);

            if(!isJumpContinue && (beanndex < noRecordIndex)){
                obj.put("right_option", exerciseBean.right_option);
                obj.put("option_result", exerciseBean.option_result);

                List<MutiExerciseOptionBean> optionBeans = exerciseBean.getOptionBeans();
                if(!ToolUtils.isListEmpty(optionBeans)){
                    for (int i = 0;i < optionBeans.size();i++){
                        MutiExerciseOptionBean mutiExerciseOptionBean = optionBeans.get(i);
                        if(mutiExerciseOptionBean != null && !TextUtils.isEmpty(exerciseBean.my_option)
                                && (mutiExerciseOptionBean.id + "").equals(exerciseBean.my_option)){
                            mutiExerciseOptionBean.setAnswerIndex(i);
                        }
                    }
                }
            }else {
                obj.put("right_option", rightOptionId);
                obj.put("option_result", option_result);
            }

            if ((Integer.parseInt(exerciseBean.exercises_type) == Constants.TYPE_ENGLISH_WORDS_EXERCISE && exerciseBean.exercises_level.equals("2"))
                    || (Integer.parseInt(exerciseBean.exercises_type) == Constants.TYPE_SYNC_EXERCISE && exerciseBean.exercises_level.equals("1"))
                    || !isJumpContinue && (beanndex < noRecordIndex)
                    || isJumpContinue) {
                //如果是单词练习题型3 或者 同步练习题型2（填空题）：
                obj.put("my_option", exerciseBean.my_option);
            } else {
                obj.put("my_option", my_option);
            }
        } catch (JSONException je) {
            Log.d(TAG, je.toString());
            je.printStackTrace();
        }

        if(isJumpContinue){
            rightOptionId = 0;
            option_result = 0;
        }

        return obj;
    }

    private void initSelectTopicArguments(MutiExerciseBean exerciseBean) {
        MutiExerciseOptionBean selectOptionBean = null;
        List<MutiExerciseOptionBean> optionLis = exerciseBean.getOptionBeans();
        for (MutiExerciseOptionBean optionBean : optionLis) {
            if (optionBean.getAnswerIndex() >= 0) {
                selectOptionBean = optionBean;
            }
            if (optionBean.option_result == 1) {
                rightOptionId = optionBean.id;
            }
        }

        switch (Integer.parseInt(exerciseBean.exercises_type)) {
            case Constants.TYPE_STRANGE_WORDS_EXERCISE://生字练习
            case Constants.TYPE_HEARING_EXERCISE://听力练习
                if (selectOptionBean != null) {
                    option_result = selectOptionBean.option_result;
                    my_option = selectOptionBean.id;
                }
                break;
            case Constants.TYPE_SPEAKING_EXERCISE://口语练习
                my_option = Integer.parseInt(exerciseBean.my_option);
                break;
            case Constants.TYPE_ENGLISH_WORDS_EXERCISE://单词练习
                switch (Integer.parseInt(exerciseBean.exercises_level)) {
                    case 0://题型1
                    case 1://题型2
                    case 3://题型4
                        if (selectOptionBean != null) {
                            option_result = selectOptionBean.option_result;
                            my_option = selectOptionBean.id;
                        }
                        break;
                    case 2://题型3
                        rightOptionId = 1;
                        if (TextUtils.isEmpty(exerciseBean.my_option)) {
                            option_result = 0;
                        } else {
                            if (exerciseBean.my_option.equalsIgnoreCase(exerciseBean.answer)) {
                                option_result = 1;
                            } else {
                                option_result = 0;
                            }
                        }
                        break;
                }
                break;
            case Constants.TYPE_SYNC_EXERCISE://同步练习
            case Constants.TYPE_CHINESE_SECT_EXERCISE://语文分科练习
            case Constants.TYPE_MACH_SECT_EXERCISE://数学分科练习
            case Constants.TYPE_ENGLISH_SECT_EXERCISE://英语分科练习
                switch (Integer.parseInt(exerciseBean.exercises_level)) {
                    case 0://选择题
                        if (selectOptionBean != null) {
                            option_result = selectOptionBean.option_result;
                            my_option = selectOptionBean.id;
                        }
                        break;
                    case 1://填空题
                        rightOptionId = 1;
                        if (TextUtils.isEmpty(exerciseBean.my_option)) {
                            option_result = 0;
                        } else {
                            if (exerciseBean.my_option.equalsIgnoreCase(exerciseBean.answer)) {
                                option_result = 1;
                            } else {
                                option_result = 0;
                            }
                        }
                        break;
                }
                break;
        }
    }

    @Override
    public void onPageSelected(int position) {
        pageIndex = position;
        tvCurrentNum.setText("(" + (position + 1));

        playAudio();
        showCollect();

        if(examFragmentAdapter != null && (pageIndex == examFragmentAdapter.getCount()-1)
                && jumpType != Constants.JUMP_TYPE_TOPICS_WATCH
                && jumpType != Constants.JUMP_TYPE_WRONG_TOPIC_WATCH) {
            completeExam = true;
            btnNextTopic.setText("提交");
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {
        //do nothing
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        //do nothing
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.exam_title_img://收藏按钮
                if(examFragmentAdapter == null || examFragmentAdapter.getCount() == 0){
                    return;
                }
                MutiExerciseBean exerciseBean = ToolUtils.getMutiExerciseBean(examFragmentAdapter.getItem(pageIndex));

                if (exerciseBean.child_collect == 1) {
                    doPostCollect(2);
                } else {
                    doPostCollect(1);
                }
                break;
            case R.id.btn_next_topic://下一题
                if (completeExam) {
                    if(exercisePaperBean == null){
                        showToast("练习数据为null");
                        break;
                    }
                    if(examType == Constants.TYPE_SMART_EXERCISE){
                        postSmartRecord();
                    }else {
                        postPaperRecord();
                    }
                    break;
                }
                if (examFragmentAdapter != null && (pageIndex + 1 == examFragmentAdapter.getCount())) {
                    showToast("已经是最后一题了");
                    break;
                }
                Message msg = scrollHandler.obtainMessage(0);
                msg.arg1 = pageIndex + 1;
                scrollHandler.sendMessage(msg);
                tvCurrentNum.setText("(" + (pageIndex + 1));
                if (!(jumpType == Constants.JUMP_TYPE_TOPICS_WATCH || jumpType == Constants.JUMP_TYPE_WRONG_TOPIC_WATCH)) {
                    btnNextTopic.setEnabled(false);
                }
                break;
            default:
                break;
        }
    }

    /**
     * 收藏和取消收藏
     *
     * @param collectType 1:收藏试题2:取消收藏试题
     */
    private void doPostCollect(final int collectType) {
        int childId = shuShanApplication.getCurrentChildId();
        if(examFragmentAdapter == null || examFragmentAdapter.getCount() == 0){
            return;
        }
        MutiExerciseBean exerciseBean = ToolUtils.getMutiExerciseBean(examFragmentAdapter.getItem(pageIndex));
        UrlParse urlParse = new UrlCommParse(this, UrlConst.BASE_URL).appendRegion(UrlConst.NEW_TYPE_TOPIC_COLLECT);
        UrlParse paramParse = new UrlCommParse(this)
                .putValue("child_id", childId)
                .putValue("exercise_id", exerciseBean.id)
                .putValue("subject_id", exerciseBean.subject_id)
                .putValue("exercises_type", examType)
                .putValue("type", collectType + "");

        showWaitDialog();
        NetHelper.create()
                .url(urlParse.toStringOnlyHeader())
                .param(paramParse.toStringOnlyParam())
                .request(RequestType.REQUEST_TYPE_POST, new NetStrCommListener() {
                    @Override
                    protected void onCommon() {
                        dismissWaitDialog();
                    }

                    @Override
                    protected void onSuccess(String data) {
                        dealCollect();
                    }

                    @Override
                    protected void onError(CallbackCode errorCode, NetRetBean netRetBean) {
                        showNetError(netRetBean);
                    }
                });
    }

    private void dealCollect() {
        if(examFragmentAdapter == null || examFragmentAdapter.getCount() == 0){
            return;
        }
        MutiExerciseBean exerciseBean = ToolUtils.getMutiExerciseBean(examFragmentAdapter.getItem(pageIndex));
        if (exerciseBean.child_collect == 1) {
            examButton.setBackgroundResource(R.drawable.exam_title_uncollect);
            exerciseBean.child_collect = 0;
        } else {
            examButton.setBackgroundResource(R.drawable.exam_title_collected);
            exerciseBean.child_collect = 1;
        }
    }

    private void playAudio(){
        //进入界面播放音频@{
        if(examFragmentAdapter == null){
            Log.d(TAG,"playAudio : examFragmentAdapter == null");
            return;
        }

        MutiExerciseBean exerciseBean = ToolUtils.getMutiExerciseBean(examFragmentAdapter.getItem(pageIndex));
        if(!TextUtils.isEmpty(exerciseBean.voice)){
            int[] types = ToolUtils.getExamFragmentType(examFragmentAdapter.getItem(pageIndex));
            AnimationDrawable animationDrawable = null;
            String audioPath = "";
            if(types[0] == Constants.TYPE_SPEAKING_EXERCISE){
                animationDrawable = ((SpeakingExamFragment)(examFragmentAdapter.getItem(pageIndex))).getAudioPlayAnim();
                audioPath = ((SpeakingExamFragment)(examFragmentAdapter.getItem(pageIndex))).getAudioPath(exerciseBean);
            }else if(types[0] == Constants.TYPE_ENGLISH_WORDS_EXERCISE){
                if(types[1] == 0){
                    animationDrawable = ((EnglishWordsExamFragment)(examFragmentAdapter.getItem(pageIndex))).getPlayAnim();
                    audioPath = ((EnglishWordsExamFragment)(examFragmentAdapter.getItem(pageIndex))).getAudioPath(exerciseBean);
                }else if(types[1] == 1){
                    animationDrawable = ((EnglishWordsExam3Fragment)(examFragmentAdapter.getItem(pageIndex))).getPlayAnim();
                    audioPath = ((EnglishWordsExam3Fragment)(examFragmentAdapter.getItem(pageIndex))).getAudioPath(exerciseBean);
                }
            }else if(types[0] == Constants.TYPE_HEARING_EXERCISE){
                animationDrawable = ((HearingExamFragment)(examFragmentAdapter.getItem(pageIndex))).getPlayAnim();
                audioPath = ((HearingExamFragment)(examFragmentAdapter.getItem(pageIndex))).getAudioPath(exerciseBean);
            }
            if(animationDrawable != null){
                ExamAudioPlayUtil.playAudio(audioPath,animationDrawable);
            }
        }
        //@}
    }

    private void showCollect() {
        if(examFragmentAdapter == null || examFragmentAdapter.getCount() == 0){
            return;
        }
        MutiExerciseBean exerciseBean = ToolUtils.getMutiExerciseBean(examFragmentAdapter.getItem(pageIndex));
        if (exerciseBean.child_collect == 1) {
            examButton.setBackgroundResource(R.drawable.exam_title_collected);
        } else {
            examButton.setBackgroundResource(R.drawable.exam_title_uncollect);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        IntentFilter intentFilter = new IntentFilter(Constants.SPEAKING_EXAM_ALREAD_SCORE_ACTION);
        LocalBroadcastManager.getInstance(this).registerReceiver(alreadyScoreReceiver, intentFilter);
        shuShanApplication.setExaming(true);
    }

    @Override
    protected void onPause() {
        super.onPause();

        LocalBroadcastManager.getInstance(this).unregisterReceiver(alreadyScoreReceiver);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        doneFinish = true;

        //回收动画音频对象
        rightAnimation = null;
        wrongAnimation = null;
        soundPool.release();
        soundPool = null;
        soundIdMap = null;

        DownloadUtil.getInstance().setOnSourceExistListener(null);
        DownloadUtil.getInstance().setOnDownloadFinishedListener(null);

        if (wakeLock != null) {
            wakeLock.release();
            wakeLock = null;
        }

        shuShanApplication.setExaming(false);
        System.gc();

        setResult(100);
    }

    @Override
    protected void onTitleBack() {
        if (jumpType > 1 && jumpType != Constants.JUMP_TYPE_EXAM_CONTINUE) {//查看习题和查看错题
            onBackAction();
        } else {
            showNoBackWarnDialog();
        }
    }

    private void showNoBackWarnDialog() {
        new CustomDialog.Builder(this)
                .setTitle("温馨提示")
                .setMessage("答题期间，没有答完题目，数据尚未上报，不建议退出，是否退出？")
                .setNegativeButton("退出", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                        if (!(examType == Constants.TYPE_SMART_EXERCISE
                                || examType == Constants.TYPE_SPEAKING_EXERCISE
                                || examType == Constants.TYPE_ORAL_CALCULATE_EXERCISE
                                || exercisePaperBean == null)) {
                            Intent intent = new Intent(MixedExamActivity.this,PostExerciseServer.class);
                            intent.putExtra("exercisesType",examType);
                            intent.putExtra("paperId",exercisePaperBean.paperInfoBean.id);
                            intent.putExtra("answerJson",getAnswerJsonArr(true));
                            startService(intent);
                        }

                        DownloadUtil.getInstance().setOnSourceExistListener(null);
                        DownloadUtil.getInstance().setOnDownloadFinishedListener(null);
                        onBackAction(200);
                    }
                })
                .setPositiveButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .create().show();
    }

    private class AlreadyScoreReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(Constants.SPEAKING_EXAM_ALREAD_SCORE_ACTION)) {
                btnNextTopic.setEnabled(false);
            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK){
            if (jumpType > 1 && jumpType != Constants.JUMP_TYPE_EXAM_CONTINUE) {//查看习题和查看错题
                onBackAction();
            } else {
                showNoBackWarnDialog();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void jumpNoRecord() {
        noRecordIndex = 0;

        if(examType == Constants.TYPE_SYNC_EXERCISE){
            boolean isOver = false;
            for (MutiExerciseBean mutiExerciseBean : chineseExerciseBeans){
                if(TextUtils.isEmpty(mutiExerciseBean.my_option)){
                    isOver = true;
                    break;
                }else {
                    noRecordIndex++;
                }
            }

            if(!isOver){
                for (MutiExerciseBean mutiExerciseBean : mathExerciseBeans){
                    if(TextUtils.isEmpty(mutiExerciseBean.my_option)){
                        isOver = true;
                        break;
                    }else {
                        noRecordIndex++;
                    }
                }
            }

            if(!isOver){
                for (MutiExerciseBean mutiExerciseBean : englishExerciseBeans){
                    if(TextUtils.isEmpty(mutiExerciseBean.my_option)){
                        break;
                    }else{
                        noRecordIndex++;
                    }
                }
            }

        }else if(examType == Constants.TYPE_STRANGE_WORDS_EXERCISE){
            for (MutiExerciseBean mutiExerciseBean : chineseExerciseBeans){
                if(TextUtils.isEmpty(mutiExerciseBean.my_option)){
                    break;
                }else {
                    noRecordIndex++;
                }
            }
        }else if(examType == Constants.TYPE_SPEAKING_EXERCISE){
            for (MutiExerciseBean mutiExerciseBean : englishExerciseBeans){
                if(TextUtils.isEmpty(mutiExerciseBean.my_option)){
                    break;
                }else {
                    noRecordIndex++;
                }
            }
        }else if(examType == Constants.TYPE_ENGLISH_WORDS_EXERCISE){
            for (MutiExerciseBean mutiExerciseBean : englishExerciseBeans){
                if(TextUtils.isEmpty(mutiExerciseBean.my_option)){
                    break;
                }else {
                    noRecordIndex++;
                }
            }
        }else if(examType == Constants.TYPE_HEARING_EXERCISE){
            for (MutiExerciseBean mutiExerciseBean : englishExerciseBeans){
                if(TextUtils.isEmpty(mutiExerciseBean.my_option)){
                    break;
                }else {
                    noRecordIndex++;
                }
            }
        }else if(examType == Constants.TYPE_CHINESE_SECT_EXERCISE){
            for (MutiExerciseBean mutiExerciseBean : chineseExerciseBeans){
                if(TextUtils.isEmpty(mutiExerciseBean.my_option)){
                    break;

                }else {
                    noRecordIndex++;
                }
            }
        }else if(examType == Constants.TYPE_MACH_SECT_EXERCISE){
            for (MutiExerciseBean mutiExerciseBean : mathExerciseBeans){
                if(TextUtils.isEmpty(mutiExerciseBean.my_option)){
                    break;
                }else {
                    noRecordIndex++;
                }
            }
        }else if(examType == Constants.TYPE_ENGLISH_SECT_EXERCISE){
            for (MutiExerciseBean mutiExerciseBean : englishExerciseBeans){
                if(TextUtils.isEmpty(mutiExerciseBean.my_option)){
                    break;
                }else {
                    noRecordIndex++;
                }
            }
        }

        Log.i(TAG,"noRecordIndex=" + noRecordIndex);

        Message msg = scrollHandler.obtainMessage(0);
        msg.arg1 = noRecordIndex;
        scrollHandler.sendMessage(msg);
    }
}